(function () {
    window.spawn = window.spawn || function (gen) {
        function continuer(verb, arg) {
            var result;
            try {
                result = generator[verb](arg);
            } catch (err) {
                return Promise.reject(err);
            }
            if (result.done) {
                return result.value;
            } else {
                return Promise.resolve(result.value).then(onFulfilled, onRejected);
            }
        }
        var generator = gen();
        var onFulfilled = continuer.bind(continuer, 'next');
        var onRejected = continuer.bind(continuer, 'throw');
        return onFulfilled();
    };

    window.showModalDialog = window.showModalDialog || function (url, arg, opt, resizable) {
        let index = getDialogNumber()
        url = url || ''; //URL of a dialog
        arg = arg || null; //arguments to a dialog
        var caller = arguments.callee.caller.toString();
        var dialog = document.body.appendChild(document.createElement('dialog'));
        dialog.setAttribute('id', "dialog" + index);
        dialog.setAttribute('style', opt);
        let dialogHtml =
            '<div id="dialog-header' + index + '" class="dlg_top" draggable="true" style="position: relative;height: 28px;z-index: 3;background: #c2d7ea;border-top-left-radius: 3px;border-top-right-radius: 3px;border-bottom: 1px solid #eec;cursor: move;opacity: 0.9;">'
            + '<div id="dialog-title' + index + '" class="dlg_top" style="line-height: 28px;padding-left: 20px;"></div>'
            + '<a href="#" id="dialog-close' + index + '" style="position: absolute; top: 0px; right: 5px; font-size: 20px; color: #000; text-decoration: none; outline: none;">&times;</a>'
            + '</div>'
            + '<div style="width: 100%; height: 95%;overflow: auto;background:white;">'
            + '<iframe id="dialog-body' + index + '" onload="iframeOnload(' + index + ');" src="' + url + '" style="border: 0; width: 100%; height: 99%;"></iframe>'
            + '</div>';
        if (resizable) {
            dialogHtml = dialogHtml
                + '<div id="dlg_right_bottom' + index + '" style="width: 15px;height: 15px;position: absolute;right: 0;bottom: 0;cursor: nw-resize;overflow: hidden;font-size: 12px;text-align: center;line-height: 15px;float: right;z-index: 4;"></div>';
        }
        dialog.innerHTML = dialogHtml;
        document.getElementById('dialog-body' + index).contentWindow.dialogArguments = arg;
        document.getElementById('dialog-close' + index).addEventListener('click', function (e) {
            e.preventDefault();
            dialog.close();
        });
        bindDrag('dialog-header' + index)
        if (resizable) {
            bindResizable(index);
        }
        dialog.showModal();
        //if using yield or async/await
        if (caller.indexOf('yield') >= 0 || caller.indexOf('await') >= 0) {
            return new Promise(function (resolve, reject) {
                dialog.addEventListener('close', function () {
                    var returnValue = document.getElementById('dialog-body' + index).contentWindow.returnValue;
                    document.body.removeChild(dialog);
                    resolve(returnValue);
                });
            });
        }
    };
})();

function iframeOnload(index) {
    console.log('iframeOnload')
    if (document.getElementById("dialog-body"+index).contentWindow.document) {
        let currentDocument = document.getElementById("dialog-body"+index).contentWindow.document;
        console.log(currentDocument.title)
        document.getElementById('dialog-title'+index).innerHTML = currentDocument.title
        $(currentDocument).find('.contents').width("100%")
    }
}

function bindResizable(index) {
    var mouseStart = {};
    var divStart = {};
    var el_dialog = document.getElementById("dialog"+index);
    var el_dlg_right_bottom = document.getElementById("dlg_right_bottom"+index);
    var minHeight = $(el_dialog).attr("minheight");
    var minWidth = $(el_dialog).attr("minwidth");
    // drag from right bottom
    el_dlg_right_bottom.onmousedown = function (ev) {
        var oEvent = ev || event;
        mouseStart.x = oEvent.clientX;
        mouseStart.y = oEvent.clientY;
        divStart.x = el_dlg_right_bottom.offsetLeft;
        divStart.y = el_dlg_right_bottom.offsetTop;
        if (el_dlg_right_bottom.setCapture) {
            el_dlg_right_bottom.onmousemove = doDragToRightBottom;
            el_dlg_right_bottom.onmouseup = stopDragToRightBottom;
            el_dlg_right_bottom.setCapture();
        }
        else {
            document.addEventListener("mousemove", doDragToRightBottom, true);
            document.addEventListener("mouseup", stopDragToRightBottom, true);
        }
    };
    function doDragToRightBottom(ev) {
        var oEvent = ev || event;
        var l = oEvent.clientX - mouseStart.x + divStart.x;
        var t = oEvent.clientY - mouseStart.y + divStart.y;
        var w = l + el_dlg_right_bottom.offsetWidth;
        var h = t + el_dlg_right_bottom.offsetHeight;
        if (w < el_dlg_right_bottom.offsetWidth) {
            w = el_dlg_right_bottom.offsetWidth;
        }
        else if (w > document.documentElement.clientWidth - el_dialog.offsetLeft) {
            w = document.documentElement.clientWidth - el_dialog.offsetLeft - 2;
        }
        if (h < el_dlg_right_bottom.offsetHeight) {
            h = el_dlg_right_bottom.offsetHeight;
        }
        else if (h > document.documentElement.clientHeight - el_dialog.offsetTop) {
            h = document.documentElement.clientHeight - el_dialog.offsetTop - 2;
        }
        if (w < minWidth) return;
        el_dialog.style.width = w + "px";
        if (h < minHeight) return;
        el_dialog.style.height = h + "px";
    };
    function stopDragToRightBottom() {
        if (el_dlg_right_bottom.releaseCapture) {
            el_dlg_right_bottom.onmousemove = null;
            el_dlg_right_bottom.onmouseup = null;
            el_dlg_right_bottom.releaseCapture();
        }
        else {
            document.removeEventListener("mousemove", doDragToRightBottom, true);
            document.removeEventListener("mouseup", stopDragToRightBottom, true);
        }
    }
};


function bindDrag(id) {
    var oldmousex = 0;
    var oldmousey = 0;
    var oldposx = 0;
    var oldposy = 0;
    let headerDiv = $('#' + id)[0]
    let curDialog = getCurDialog();
    headerDiv.ondragstart = function (ev) {
        var ev = ev || window.event;
        oldmousex = ev.screenX;
        oldmousey = ev.screenY;
        oldposx = curDialog.offsetLeft;
        oldposy = curDialog.offsetTop;
    }
    headerDiv.ondrag = function (ev) {
        var ev = ev || window.event;
        if (ev.screenX != 0 && ev.screenY != 0) {
            var newposx = ev.screenX - oldmousex;
            var newposy = ev.screenY - oldmousey;
            curDialog.style.left = (oldposx + newposx) + "px";
            curDialog.style.top = (oldposy + newposy) + "px";
        }
    }
}